﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NetworkManager : SingletonMono<NetworkManager> {

    string ip_debug = "192.168.4.234";
    string ip_aliyun = "47.92.212.14";
    string ip_fwtDebug = "192.168.4.166";

    int port = 8000;

    SocketClient client;

    Queue<ByteBuffer> queue = new Queue<ByteBuffer>();

    HandlerCenter center = new HandlerCenter();//消息分发器

    void Start () {
        
	}
	
    public void Init(NetMode mode)
    {
        switch (mode)
        {
            case NetMode.Debug:
                client = new SocketClient(ip_debug, port);
                break;
            case NetMode.Release:
                client = new SocketClient(ip_aliyun, port);
                break;
            case NetMode.fwtDebug:
                client = new SocketClient(ip_fwtDebug, port);
                break;
            default:
                break;
        }
    }
    //生命周期的函数都在主线程
    void Update () {
		if(queue.Count>0)
        {
            ByteBuffer buffer = queue.Dequeue();//主线程把数据读取出来
            center.OnReceive(buffer);
        }
	}

    public void OnReceive(ByteBuffer buffer)
    {
        queue.Enqueue(buffer);//网络读取子线程，把数据加入到队列中
    }

    public void Send<T>(Protocol cmd,T t) where T:ProtoBuf.IExtensible
    {
        byte[] data = Util.Serilize(t);
        client.Send((int)cmd, data);
    }

    /// <summary>
    /// 游戏推出时，关闭socket连接，通知服务器
    /// </summary>
    void OnApplicationQuit()
    {
        client.Close();
    }
}
